package com.xdemo.personal.httpserver;

import org.jboss.netty.handler.codec.http.HttpMessage;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpVersion;

import com.xdemo.core.MessageType;
import com.xdemo.msg.HttpBean;
import com.xdemo.msg.IMessage;
import com.xdemo.msg.IMessageRecognizer;
import com.xdemo.personal.httpserver.msg.FileUploadUnknownErrorMsg;

public class PersonalHttpDecoder extends HttpRequestDecoder {
	
	private final IMessageRecognizer<String,HttpBean> recognizer;
	
	private final FileUploadUnknownErrorMsg unknownMsg;

	public PersonalHttpDecoder(IMessageRecognizer<String,HttpBean> recognizer) {
		this.recognizer = recognizer;
		HttpBean _bean = new HttpBean();
		_bean.setVersion(HttpVersion.HTTP_1_1);
		_bean.setMethod(HttpMethod.POST);
		_bean.setUri(MessageType.FileUploadUnknownError);
		unknownMsg = new FileUploadUnknownErrorMsg(_bean);
		unknownMsg.setChunked(false);
	}

	@Override
	protected HttpMessage createMessage(String[] initialLine) throws Exception {
		HttpBean _bean = new HttpBean();
		IMessage<String> _msg = null;
		try{
			_bean.setVersion(HttpVersion.valueOf(initialLine[2]));
			_bean.setMethod(HttpMethod.valueOf(initialLine[0]));
			_bean.setUri(initialLine[1]);
			_msg = recognizer.createMessage(_bean);
			if(_msg == null || !(_msg instanceof HttpMessage)) {
				return super.createMessage(initialLine);
			}
		}catch(Exception e) {
			return unknownMsg;
		}
		return (HttpMessage)_msg;
	}

}
